﻿using System;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Channels;
using System.ServiceModel.Configuration;

namespace DragDraw.Service
{
    public class PollingDuplexServiceHostFactory : ServiceHostFactoryBase
    {
        public override ServiceHostBase CreateServiceHost(string constructorString,
            Uri[] baseAddresses)
        {
            //return new PollingDuplexSimplexServiceHost(baseAddresses);

            PollingDuplexSimplexServiceHost serviceHost = new PollingDuplexSimplexServiceHost(baseAddresses);

            System.ServiceModel.Description.ServiceMetadataBehavior smb = serviceHost.Description.Behaviors.Find<System.ServiceModel.Description.ServiceMetadataBehavior>();
            if (smb != null)
            {
                smb.HttpGetEnabled = true;

            }
            else
            {
                smb = new System.ServiceModel.Description.ServiceMetadataBehavior();
                smb.HttpGetEnabled = true;
                serviceHost.Description.Behaviors.Add(smb);
            }

            return serviceHost;
        }
    }

    class PollingDuplexSimplexServiceHost : ServiceHost
    {
        public PollingDuplexSimplexServiceHost(params System.Uri[] addresses)
        {
            base.InitializeDescription(typeof(UserDuplexService), new UriSchemeKeyedCollection(addresses));
        }

        protected override void InitializeRuntime()
        {
            // Define the binding and set time-outs.
            PollingDuplexBindingElement pdbe = new PollingDuplexBindingElement()
            {
                ServerPollTimeout = TimeSpan.FromSeconds(10),
                InactivityTimeout = TimeSpan.FromMinutes(1)
            };

            // Add an endpoint for the given service contract.
            this.AddServiceEndpoint(
                typeof(IUserDuplexService),
                new CustomBinding(
                    pdbe,
                    new TextMessageEncodingBindingElement(
                    MessageVersion.Soap11,
                    System.Text.Encoding.UTF8),
                    new HttpTransportBindingElement()),
                    "");

            base.InitializeRuntime();
        }
    }
}